<template>
  <div class="toolbar">
    <div class="leftTool">
      <el-button
        type="primary"
        v-if="!isImportMode"
        size="small"
        @click="handleRelation"
        >删除关系连线</el-button
      >
      <el-divider direction="vertical" v-if="!isImportMode"></el-divider>
      <el-button
        type="primary"
        v-if="!isImportMode"
        size="small"
        @click="handleAutoZoom"
        class=""
      >
        适应画布
      </el-button>
      <!-- <el-divider direction="vertical" v-if="!isImportMode"></el-divider> -->
      <!-- <el-button
        @click="cleanAllData"
        v-if="!isImportMode"
        size="small"
        type="primary"
        >清空</el-button
      > -->
    </div>
    <div class="rightButton">
      <!-- <el-button
        @click="consoleData"
        v-if="!isImportMode"
        size="small"
        type="primary"
        >保存位置</el-button
      > -->
      <el-button
        @click="handleSaveImportInfo"
        size="small"
        type="primary"
        v-if="isImportMode"
        >保存导入信息</el-button
      >
      <el-button
        @click="cancelImportInfo"
        size="small"
        type="primary"
        v-if="isImportMode"
        >取消</el-button
      >
    </div>
  </div>
</template>

<script>
import eventBus from '../../utils/eventBus'
import Util from '@antv/g6/src/util'
import { uniqueId, getBox } from '../../utils'
import {
  saveNodeCoordinate,
  saveImportKnowledgeGraph
} from '@/api/knowledgeAddition/index'

import { saveKnowledgeGraph } from '@/api/newknowledge/index.js'

export default {
  components: {},
  data() {
    return {
      page: {},
      graph: {},
      redoList: [],
      undoList: [],
      editor: null,
      command: null,
      selectedItem: [],
      multiSelect: false,
      addGroup: false,
      popUpObj: {
        state: false
      },
      isImportMode: false
    }
  },
  created() {
    this.init()
    this.bindEvent()
    // 监听上传页面触发的事件，清空画布
    this.$bus.$on('cleanCanvas', () => {
      this.isImportMode = true
      this.$store.dispatch('drawer/setisshowcontext', false)
      this.cleanAllData()
    })

    this.$bus.$on('clearCanvas', () => {
      this.cleanAllData()
    })
  },
  watch: {
    selectedItem(val) {
      if (val && val.length > 1) {
        this.addGroup = true
      } else {
        this.addGroup = false
      }
    }
  },
  mounted() {
    this.$bus.$on('autoCanvas', () => {
      this.handleAutoZoom()
    })
    this.$bus.$on('exitImportMode', () => {
      this.isImportMode = false
    })
    this.bindEvent()
  },
  methods: {
    init() {
      const { editor, command } = this.$parent
      this.editor = editor
      this.command = command
    },
    bindEvent() {
      let self = this
      eventBus.$on('afterAddPage', page => {
        self.page = page
        self.graph = self.page.graph
      })
      eventBus.$on('add', data => {
        this.redoList = data.redoList
        this.undoList = data.undoList
      })
      eventBus.$on('update', data => {
        this.redoList = data.redoList
        this.undoList = data.undoList
      })
      eventBus.$on('delete', data => {
        this.redoList = data.redoList
        this.undoList = data.undoList
      })
      eventBus.$on('updateItem', item => {
        this.command.executeCommand('update', [item])
      })
      eventBus.$on('addItem', item => {
        this.command.executeCommand('add', [item])
      })
      eventBus.$on('nodeselectchange', () => {
        this.selectedItem = this.graph.findAllByState('node', 'selected')
        this.selectedItem = this.selectedItem.concat(
          ...this.graph.findAllByState('edge', 'selected')
        )
      })
      eventBus.$on('deleteItem', () => {
        this.handleDelete()
      })
      eventBus.$on('muliteSelectEnd', () => {
        this.multiSelect = false
        this.selectedItem = this.graph.findAllByState('node', 'selected')
      })
    },
    handleUndo() {
      if (this.undoList.length > 0) this.command.undo()
    },
    handleRedo() {
      if (this.redoList.length > 0) this.command.redo()
    },
    handleRelation() {
      if (this.selectedItem.length === 0) {
        return this.$message.error('请选择要删除的关系')
      }
      if (this.selectedItem[0]._cfg.type === 'node') {
        return this.$message.error('只允许删除关系')
      }
      this.handleDelete()
    },
    handleDelete() {
      this.command.executeCommand('delete', this.selectedItem)
      this.selectedItem = []
    },
    getFormatPadding() {
      return Util.formatPadding(this.graph.get('fitViewPadding'))
    },
    getViewCenter() {
      const padding = this.getFormatPadding()
      const graph = this.graph
      const width = this.graph.get('width')
      const height = graph.get('height')
      return {
        x: (width - padding[2] - padding[3]) / 2 + padding[3],
        y: (height - padding[0] - padding[2]) / 2 + padding[0]
      }
    },
    handleZoomIn() {
      const currentZoom = this.graph.getZoom()
      this.graph.zoomTo(currentZoom + 0.5, this.getViewCenter())
    },
    handleZoomOut() {
      const currentZoom = this.graph.getZoom()
      this.graph.zoomTo(currentZoom - 0.5, this.getViewCenter())
    },
    handleToBack() {
      if (this.selectedItem && this.selectedItem.length > 0) {
        this.selectedItem.forEach(item => {
          item.toBack()
          this.graph.paint()
        })
      }
    },
    handleToFront() {
      if (this.selectedItem && this.selectedItem.length > 0) {
        this.selectedItem.forEach(item => {
          if (item.getType() === 'edge') {
            // const nodeGroup = this.graph.get("nodeGroup");
            // const edgeGroup = item.get("group");
            // nodeGroup.toFront();
            // edgeGroup.toFront()
          } else {
            item.toFront()
          }

          this.graph.paint()
        })
      }
    },
    handleAutoZoom() {
      const jsonData = this.graph.save()
      if (jsonData.edges.length == 0 && jsonData.nodes.length == 0) return
      let zoomCount = 0
      if (jsonData.edges.length < 5) {
        zoomCount = 500
      } else {
        zoomCount = 20
      }
      this.graph.fitView(zoomCount)
    },
    handleResetZoom() {
      this.graph.zoomTo(1, this.getViewCenter())
    },
    handleMuiltSelect() {
      this.multiSelect = true
      this.graph.setMode('mulitSelect')
    },
    handleAddGroup() {
      //TODO 这部分等阿里更新Group之后添加
      // const model = {
      //   id: "group" + uniqueId(),
      //   title: "添加分组"
      // };
      // // this.command.executeCommand("add", "group", model);
      // this.selectedItem.forEach(item => {
      //   console.log(item);
      // });
      //this.getPosition(this.selectedItem);
    },
    getPosition(items) {
      const boxList = []
      items.forEach(item => {
        const box = item.getBBox()
        boxList.push(getBox(box.x, box.y, box.width, box.height))
      })
      let minX1, minY1, MaxX2, MaxY2
      boxList.forEach(box => {
        if (typeof minX1 == 'undefined') {
          minX1 = box.x1
        }
        if (typeof minY1 == 'undefined') {
          minY1 = box.y1
        }
        if (typeof MaxX2 == 'undefined') {
          MaxX2 = box.x2
        }
        if (typeof MaxY2 == 'undefined') {
          MaxY2 = box.y2
        }
        if (minX1 > box.x1) {
          minX1 = box.x1
        }
        if (minY1 > box.y1) {
          minY1 = box.y1
        }
        if (MaxX2 < box.x2) {
          MaxX2 = box.x2
        }
        if (MaxY2 < box.y2) {
          MaxY2 = box.y2
        }
      })
      const width = MaxX2 - minX1,
        height = MaxY2 - minY1,
        x = minX1 + width / 2,
        y = minY1 + height / 2,
        id = 'team' + uniqueId()
      const model = {
        id: id,
        width,
        height,
        x,
        y,
        shape: 'teamNode'
      }
      this.command.executeCommand('add', model)
      // const item = this.graph.findById(id);
      // item.get("group").toBack();
      // const edgeGroup = this.graph.get("edgeGroup");
      // edgeGroup.toFront();
      // this.graph.paint();
    },
    // 保存图坐标
    consoleData() {
      const jsonData = this.graph.save()
      const data = {
        nodes: jsonData.nodes
      }
      saveNodeCoordinate(data).then(res => {
        if (res.data.code == 200) {
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    // 清空图数据
    cleanAllData() {
      let newData = '{"nodes":[],"edges":[],"groups":[]}'
      newData = JSON.parse(newData)
      this.graph.clear()
      this.graph.changeData(newData)
    },
    // 导入文件方法
    exportJsonData() {
      this.popUpObj.state = true
      this.$emit('getPopupObj', this.popUpObj)
    },
    // 保存导入信息
    handleSaveImportInfo() {
      const jsonData = this.graph.save()
      const data = {
        nodes: jsonData.nodes,
        edges: jsonData.edges
      }
      saveKnowledgeGraph(data).then(response => {
        if (response.data.code !== 200) {
          return this.$message.error('操作失败')
        }
        this.$message.success('操作成功')
        // 保存成功后，将isImportMode置为false
        this.isImportMode = false
        this.$store.dispatch('drawer/setisshowcontext', true)
        // 调用接口重新获取数据
        this.$bus.$emit('getNewData')
        this.$store.dispatch('drawer/setisupload', false)
      })
    },
    // 取消导入信息
    cancelImportInfo() {
      this.graph.clear()
      this.$bus.$emit('getNewData')
      this.graph.render()
      this.isImportMode = false
      this.$store.dispatch('drawer/setisshowcontext', true)
      this.$message.warning('取消导入')
      setTimeout(() => {
        this.handleAutoZoom()
      }, 300)
    }
  },
  beforeDestroy() {
    eventBus.$off('afterAddPage')
    eventBus.$off('contextmenuClick')
    eventBus.$off('mousedown')
    eventBus.$off('add')
    eventBus.$off('delete')
    eventBus.$off('muliteSelectEnd')
    eventBus.$off('updateItem')
    eventBus.$off('addItem')
    this.$bus.$off('cleanCanvas')
  }
}
</script>

<style scoped>
.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0px 30px;
  width: 100%;
  height: 42px;
  border: 1px solid #2d65ad;
  box-sizing: border-box;
  box-shadow: 0px 8px 12px 0px rgba(0, 52, 107, 0.04);
}

.toolbar .command:nth-of-type(1) {
  margin-left: 24px;
}

.toolbar .command {
  box-sizing: border-box;
  width: 27px;
  height: 27px;
  margin: 0px 6px;
  border-radius: 2px;
  padding-left: 4px;
  display: inline-block;
  border: 1px solid rgba(2, 2, 2, 0);
}

.toolbar .command:hover {
  cursor: pointer;
  border: 1px solid #e9e9e9;
}

.toolbar .disable {
  color: rgba(0, 0, 0, 0.25);
}

.toolbar .separator {
  margin: 4px;
  border-left: 1px solid #e9e9e9;
}
</style>
